package com.sudo.boot.netty.reconnect;

import com.sudo.boot.netty.NettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class NettyClient {
    public static void main(String[] args) {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new NettyReconnetClientHandler(bootstrap));
                    }
                });
        // 第一次连接
        connect(bootstrap);
        // 阻塞，为了看结果
//        try {
//            System.in.read();
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
    }

    public static void connect(Bootstrap bootstrap) {
        // 连接服务器
        ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8080);
        // 异步连接
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                boolean success = channelFuture.isSuccess();
                if (!success) {
                    // 重新连接
                    Thread.sleep(1000);
                    System.out.println("重新连接中...");
                    connect(bootstrap);
//                    channelFuture.channel().eventLoop().schedule(() -> {
//                        connect(bootstrap);
//                    }, 2000, TimeUnit.MILLISECONDS);

                }else {
                    System.out.println("连接成功");
                }
            }
        });
    }
}
